<?php

namespace app\admin\controller\procurement;

use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use EasyAdmin\tool\CommonTool;
use jianyan\excel\Excel;
use Symfony\Component\DependencyInjection\Argument\BoundArgument;
use think\App;
use app\admin\model\Rule;
use app\admin\model\Category;
use app\admin\model\Supplier;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="product_maps")
 */
class ProductMaps extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\ProductMaps();

    }

    public function index()
    {

        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model
                ->withJoin(['category', 'supplier', 'rule'], 'LEFT')
                ->where($where)
                ->count();
            $list = $this->model
                ->withJoin(['category', 'supplier', 'rule'], 'LEFT')
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data = [
                'code' => 0,
                'msg' => '',
                'count' => $count,
                'data' => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="导出")
     */
    public function export()
    {
        list($page, $limit, $where) = $this->buildTableParames();

        $header = [
            ['ID', 'id'],
            ['统计分类', 'category_name'],
            ['名称', 'name'],
            ['SKU', 'sku'],
            ['工厂货号', 'item_number'],
            ['规则', 'rule_name'],
            ['生产周期', 'cycle'],
            ['自动派单', 'is_auto'],
            ['供应商', 'supplier_name'],
            ['扩展字段', 'extension'],
        ];

        !empty($where) ? ($where[0][0] == 'id' ? $where[0][0] = $this->model->getName() . '.id' : '') : [];

        $data = [];
        $list = $this->model
            ->withJoin(['category', 'supplier', 'rule'], 'LEFT')
            ->where($where)
            ->limit(1000)
            ->order($this->model->getName() . '.id', 'desc')
            ->select()
            ->toArray();

        collection($list)->map(function ($item, $key) use (&$data) {
            $data[$key]['id'] = $item['id'];
            $data[$key]['category_name'] = $item['category']['name'];
            $data[$key]['name'] = $item['name'];
            $data[$key]['sku'] = $item['sku'];
            $data[$key]['item_number'] = $item['item_number'];
            $data[$key]['rule_name'] = $item['rule']['name'];
            $data[$key]['cycle'] = $item['cycle'];
            $data[$key]['is_auto'] = $item['is_auto'] ? 'TRUE' : '';
            $data[$key]['supplier_name'] = $item['supplier']['name'];
            $data[$key]['extension'] = $item['extension'];
        });

        $title = '货号对照导出';
        $fileName = $title . '-' . date('Ymd', time());

        return Excel::exportData($data, $header, $fileName, 'xlsx');
    }


    /**
     * @NodeAnotation(title="货号模板导出",auth=false)
     */
    public function export_template()
    {

        $header = [
            ['统计分类', 'category_name'],
            ['名称', 'name'],
            ['SKU', 'sku'],
            ['工厂货号', 'item_number'],
            ['规则', 'cycle'],
            ['生产周期', 'life'],
            ['自动派单', 'is_auto'],
            ['供应商', 'supplier'],
            ['扩展字段', 'extension'],
        ];
        $title = '货号模板';
        $fileName = $title . '-' . date('Ymd', time());
        return Excel::exportData([], $header, $fileName, 'xlsx');
    }

    /**
     * @NodeAnotation(title="导入")
     */
    public function import()
    {
        $row = $this->request->get();
        if ($this->request->isAjax()) {

//            获取上传文件
            $file = $this->request->file('file');

//           读取上传文档 从第二行开始
            $data = Excel::import($file, 2);

            $category_arr = Category::field('id,name')->select()->toArray();
            $rule_arr = Rule::field('id,name')->select()->toArray();
            $supplier_arr = Supplier::field('id,name')->select()->toArray();


            $category_collection = collection($category_arr);
            $rule_collection = collection($rule_arr);
            $supplier_collection = collection($supplier_arr);

            $category_name_key = $category_collection->pluck('id', 'name')->toArray();
            $rule_name_key = $rule_collection->pluck('id', 'name')->toArray();
            $supplier_name_key = $supplier_collection->pluck('id', 'name')->toArray();

            $category_names = $category_collection->pluck('name');
            $rule_names = $rule_collection->pluck('name');
            $supplier_names = $supplier_collection->pluck('name');

            $category_names_arr = $category_names->toArray();
            $rule_names_arr = $rule_names->toArray();
            $supplier_names_arr = $supplier_names->toArray();

            $data_category = collection($data)->pluck('0');
            $data_rule = collection($data)->pluck('4');
            $data_supplier = collection($data)->pluck('7');
//            dd($category_ids_arr);

            $data_category->map(function ($item, $key) use ($category_names_arr) {
                $file_line_num = $key + 2;
                if (!in_array($item, $category_names_arr)) {
                    $this->error("您导入文件在第<{$file_line_num}>行 -统计分类- 列填写有误");
                }
            });

            $data_rule->map(function ($item, $key) use ($rule_names_arr) {
                $file_line_num = $key + 2;
                if (!in_array($item, $rule_names_arr)) {
                    $this->error("您导入文件在第<{$file_line_num}>行 -规则- 列填写有误");
                }
            });

            $data_supplier->map(function ($item, $key) use ($supplier_names_arr) {
                $file_line_num = $key + 2;
                if (!in_array($item, $supplier_names_arr)) {
                    $this->error("您导入文件在第<{$file_line_num}>行 -供应商- 列填写有误");
                }
            });

//            dd('到这里了 ');


//            总的统计  好用高效   没有统计到行
            /*            $category_ids = collection($data)->pluck('0')->merge($category_names)->unique()->count();
                        $rule_ids = collection($data)->pluck('4')->merge($rule_names)->unique()->count();
                        $supplier_ids = collection($data)->pluck('7')->merge($supplier_names)->unique()->count();

                        $count_default = $category_names->count() + $rule_names->count() + $supplier_names->count();
                        $count_new = $category_ids+$rule_ids+$supplier_ids;

                        if($count_default != $count_new){
                            $this->error('导入失败请检查导入文件内容是否含有未知名称');
                        }*/

            //          总的统计结束


//            dd($count_default,$count_new);


//            构建插入数据
            $time = time();
//            dd($category_name_key);
            $collect = collection($data)->map(function ($item) use ($time, $rule_name_key, $supplier_name_key, $category_name_key) {
                return [
                    'category_id' => $category_name_key[$item[0]],
                    'name' => $item[1],
                    'sku' => $item[2],
                    'item_number' => $item[3],
                    'rule_id' => $rule_name_key[$item[4]],
                    'cycle' => $item[5],
                    'is_auto' => ($item[6] == 'TRUE') ? 1 : 0,
                    'supplier_id' => $supplier_name_key[$item[7]],
                    'extension' => \GuzzleHttp\json_encode($item[8]),

                    'create_time' => $time,
                    'update_time' => $time
                ];
            });



            //规则，SKU，供应商 相同就更新
            $update_arr = [];
            $insert_collection = $collect->map(function ($item, $key) use (&$update_arr) {
                $where = [
                    ['rule_id', '=', $item['rule_id']],
                    ['sku', '=', $item['sku']],
                    ['supplier_id', '=', $item['supplier_id']],
                ];
                $count = $this->model->where($where)->find();

                if ($count) {
                    $item['id'] = $count->id;
                    $update_arr[] = $item;
                    return false;
                }
                return $item;
            });
            //过滤空数组
            $insert_data = array_filter($insert_collection->toArray());

            $update_status = $this->model->saveAll($update_arr);



//          可以分段插入设置$limit  insertAll($date,$limit)
            $insert_status = $this->model->insertAll($insert_data);

            ($insert_status and $update_status )? $this->success('导入成功') : $this->error('导入失败');

        }

        $this->assign('row', $row);
        return $this->fetch();
    }


}